//
//  UserProfileVC.swift
//  物料商行
//
//  Created by HaoDong Hong on 2017/9/1.
//  Copyright © 2017年 HaoDong Hong. All rights reserved.
//

import UIKit
import Alamofire
import AlamofireImage

protocol UserProfileDelegate: class {
    func imageDidChanged()
    func nameDidChanged()
}

class UserProfileVC: UITableViewController {
    
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var phoneLabel: UILabel!
    @IBOutlet weak var nameTF: UITextField!
    @IBOutlet weak var emailTF: UITextField!
    //@IBOutlet weak var menuButton: UIButton!
    
    weak var delegate: UserProfileDelegate?
    
    let backgroundQueue = DispatchQueue(label: "saveToFile")
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    var imageURL: URL!
    
    var edit = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        imageURL = documentsURL.appendingPathComponent("icon.png")
        nameTF.delegate = self
        emailTF.delegate = self

    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        getUserProfile()
    }

    @IBAction func logoutButtonDidTapped(_ button: UIButton!) {
        let request = UserRequest.logout(phone: User.phoneNumber!)
        Alamofire.request(request.fullURL, method: .post, parameters: request.bodyParams, headers: nil).response { (response) in
            if response.error != nil {
                DispatchQueue.main.async {
                    self.showError(message: "连接错误，请重试")
                }
                return
            } else {
                App.state = AppState.none
                User.clearUserData()
                Store.clearData()
                (self.revealViewController().rearViewController as! MenuVC).presentVC = .none
                DispatchQueue.main.async {
                    let loginVC = LoginController()
                    let navigationController = UINavigationController(rootViewController: loginVC)
                    
                    self.present(navigationController, animated: true, completion: {
                        self.navigationController?.popViewController(animated: true)
                        loginVC.delegate = (self.navigationController?.viewControllers[0] as! LoginDelegate)
                    }
                    )
                    
                }
            }
        }
        
    }
    
    override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
        if (indexPath.section == 0 && indexPath.row == 0) || indexPath.section == 1 {
            return indexPath
        }
        return nil
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 && indexPath.row == 0 {
            let imagePickerController = UIImagePickerController()
            imagePickerController.allowsEditing = true
            imagePickerController.delegate = self
            imagePickerController.sourceType = .photoLibrary
            
            present(imagePickerController, animated: true, completion: nil)
        }
    }
    
    func upload(with name: String?, email: String?) {
        let request = UserRequest.upload(email: email, name: name)
        Alamofire.request(request.fullURL, method: .post, parameters: request.bodyParams, headers: nil).responseJSON { (response) in
            if response.error == nil {
                self.delegate?.nameDidChanged()
                User.email = email
                User.userName = name
            }
        }
    }
    
    private func getUserProfile() {
        
        let imagePath = imageURL.path
        if FileManager.default.fileExists(atPath: imagePath) {
            imageView.image = UIImage(contentsOfFile: imagePath)
        } else {
            imageView.image = #imageLiteral(resourceName: "user")
        }
        phoneLabel.text = User.phoneNumber
        nameTF.text = User.userName
        emailTF.text = User.email
    }
    
    
    
}

extension UserProfileVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        //print("ggg")
        if let pickedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
            imageView.contentMode = .scaleAspectFit
            DispatchQueue.main.async {
                self.imageView.image = pickedImage
            }
            dismiss(animated: true, completion: nil)
            //save to dic
            
            backgroundQueue.async {
                if let pngImageData = UIImagePNGRepresentation(pickedImage) {
                    do {
                        try pngImageData.write(to: self.imageURL, options: .atomic)
                        self.delegate?.imageDidChanged()
                    } catch {  }
                }
            }
        }
    }
}

extension UserProfileVC: UITextFieldDelegate {
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        upload(with: nameTF.text, email: emailTF.text)
        return true
    }
}
